//
//  LoginViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 5/22/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "LoginViewController.h"
#import <MMDrawerController/MMDrawerController.h>
#import "DrawerTableViewController.h"
#import "MarketNavigationController.h"
#import "MarketWatchTableViewController.h"
#import "AboutNavigationController.h"
#import "AboutViewController.h"
#import "ContactNavigationController.h"
#import "ContactViewController.h"
#import "EconomicCalendarNavigationController.h"
#import "EconomicCalendarViewController.h"
#import "MarketFlowNavigationController.h"
#import "MarketFlowViewController.h"

@interface LoginViewController () <UITextFieldDelegate, DrawerTableViewControllerDelegate>
{
    UIImageView *logoView;
    UITextField *userNameField;
    UITextField *passwordField;
    UIButton *loginButton;
    UITextView *announcementTextView;
}

@property (nonatomic, strong) MMDrawerController *drawerController;
@property (nonatomic, strong) MarketNavigationController *marketCenterViewController;
@property (nonatomic, strong) AboutNavigationController *aboutCenterViewController;
@property (nonatomic, strong) ContactNavigationController *contactCenterViewController;
@property (nonatomic, strong) EconomicCalendarNavigationController *economicCenterViewController;
@property (nonatomic, strong) MarketFlowNavigationController *marketFlowCenterViewController;

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[CookieUtil sharedInstance] deleteCookie:HOST];
    [[CookieUtil sharedInstance] deleteCookie:@"https://login.mycroftcloud.com"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"LoginLogo"]];
    
    userNameField = [[UITextField alloc] init];
    userNameField.placeholder = @"username";
    userNameField.borderStyle = UITextBorderStyleRoundedRect;
    userNameField.clearButtonMode = UITextFieldViewModeWhileEditing;
    userNameField.layer.borderColor = SUMRIDGECOLOR.CGColor;
    userNameField.delegate = self;
    
    
    passwordField = [[UITextField alloc] init];
    passwordField.placeholder = @"password";
    passwordField.secureTextEntry = YES;
    passwordField.borderStyle = UITextBorderStyleRoundedRect;
    passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    passwordField.layer.borderColor = SUMRIDGECOLOR.CGColor;
    passwordField.delegate = self;
    
    loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    loginButton.layer.cornerRadius = 5.0;
    loginButton.layer.borderWidth = 1.0f;
    [loginButton setBackgroundColor:SUMRIDGECOLOR];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton setTitle:@"Sign In" forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(signin:) forControlEvents:UIControlEventTouchUpInside];
    
    announcementTextView = [[UITextView alloc] init];
    announcementTextView.text = @"The enclosed listing does not constitute a solicitation or recommendation of the individual securities contained in the listing. SumRidge Partners, LLC has not made any representation as to the suitability of the bonds listed for offering nor their creditworthiness beyond the providing of a rating provided by a nationally recognized rating agency. For Institutional Clients only. TRACE data is historical and may not reflect the current market.";
    announcementTextView.editable = NO;
    announcementTextView.selectable = NO;
    
    [self.view addSubview:logoView];
    [self.view addSubview:userNameField];
    [self.view addSubview:passwordField];
    [self.view addSubview:loginButton];
    [self.view addSubview:announcementTextView];
    
    [logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(30);
        make.size.mas_equalTo(CGSizeMake(280.0, 70.0));
    }];
    
    [userNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(110.0);
        make.size.mas_equalTo(CGSizeMake(280.0, 30.0));
    }];
    
    [passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(150.0);
        make.size.mas_equalTo(CGSizeMake(280.0, 30.0));
    }];
    
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(190.0);
        make.size.mas_equalTo(CGSizeMake(280.0, 36.0));
    }];
    
    [announcementTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-10);
        make.size.mas_equalTo(CGSizeMake(280.0, 160.0));
    }];
    
    UITapGestureRecognizer *tapSpace = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSpace:)];
    [self.view addGestureRecognizer:tapSpace];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *username = [defaults objectForKey:@"username"];
    NSString *password = [defaults objectForKey:@"password"];
    
    if (username != nil) {
        userNameField.text = username;
        passwordField.text = password;
//        [self signinLocal:nil];
        [self signin:nil];
    }
}

- (void)signinLocal:(id)sender {
    NSDictionary *params = @{
                             @"counterPartyID" : @"1",
                             @"firstName" : @"first",
                             @"lastName" : @"last"
                             };
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"application/json"]];
    [manager POST:LOGINLOCAL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        DDLogVerbose(@"Request https://login.mycroftcloud.com response:\n%@", responseString);
        NSDictionary *dictionary = [responseString objectFromJSONString];
        DDLogVerbose(@"Watchlist data is:\n%@", dictionary);
        NSNumber *success = [dictionary objectForKey:@"success"];
        
        if ([success intValue] == 1) {
            DrawerTableViewController *leftSideDrawerViewController = [[DrawerTableViewController alloc] init];
            leftSideDrawerViewController.delegate = self;
            
            MarketWatchTableViewController *marketWatchViewController = [[MarketWatchTableViewController alloc] init];
            self.marketCenterViewController = [[MarketNavigationController alloc] initWithRootViewController:marketWatchViewController];
            
            self.drawerController = [[MMDrawerController alloc] initWithCenterViewController:self.marketCenterViewController leftDrawerViewController:leftSideDrawerViewController];
            [self.drawerController setShowsShadow:NO];
            [self.drawerController setRestorationIdentifier:@"MMDrawer"];
            [self.drawerController setMaximumLeftDrawerWidth:220.0];
            [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModePanningNavigationBar];
            [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
            [self presentViewController:self.drawerController animated:YES completion:nil];
        } else {
            DDLogError(@"Login Error");
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        DDLogError(@"Request https://login.mycroftcloud.com error:\n%@", error);
        NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        DDLogError(@"Login Error Message:\n%@", result);
    }];
}

- (void)signin:(id)sender {
    if ([userNameField.text isEqualToString:@""]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Username cannot be empty.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        return;
    }
    
    if ([passwordField.text isEqualToString:@""]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Password cannot be empty.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        return;
    }
    
    [userNameField resignFirstResponder];
    [passwordField resignFirstResponder];
    
    //test account: jjiang Smrd1221
    NSDictionary *params = @{@"SMENC": @"ISO-8859-1",
                             @"SMLOCALE": @"US-EN",
                             @"smauthreason": @"0",
                             @"smretries": @"1",
                             @"smerrorpage": @"https://www.sumridge.com/index.php",
                             @"postpreservationdata": @"",
                             @"USER": userNameField.text,
                             @"PASSWORD": passwordField.text,
                             @"counterPartyID": @"1"};
    
    NSString *loginUrl = @"https://login.mycroftcloud.com/affwebservices/sumridge/redirect.jsp?SMPORTALURL=https%3A%2F%2Flogin.mycroftcloud.com%2Faffwebservices%2Fpublic%2Fsaml2sso%3FSPID%3D100%26RelayState%3Dhttp%3A%2F%2Fwww.sumridge.com";
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    [manager POST:loginUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSURL *formPostUrl = task.response.URL;
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        DDLogVerbose(@"Request https://login.mycroftcloud.com response:\n%@", responseString);
        
        if ([responseString containsString:@"SAMLResponse"]) {
            [self signInWithSAML:responseString];
            return;
        }
        
        [manager POST:[formPostUrl absoluteString] parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            DDLogVerbose(@"formPostUrl response is:\n%@", responseString);
            [self signInWithSAML:responseString];
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            DDLogError(@"Login Error: %@", error);
            NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
            DDLogError(@"Login Error Message:\n%@", result);
        }];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        DDLogError(@"Request https://login.mycroftcloud.com error:\n%@", error);
        NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        DDLogError(@"Login Error Message:\n%@", result);
    }];
}

- (void)tapSpace:(id)sender {
    [userNameField resignFirstResponder];
    [passwordField resignFirstResponder];
}

- (void)signInWithSAML:(NSString *)contentString {
    if ([contentString containsString:@"Login failed, invalid credentials."]) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Username or Password error.";
        hud.detailsLabelText = @"Please try again.";
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // Do something...
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        return;
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:userNameField.text forKey:@"username"];
    [defaults setValue:passwordField.text forKey:@"password"];
    
    NSArray *stringArray1 = [contentString componentsSeparatedByString:@"action=\""];
    NSString *formString = stringArray1[1];
    NSArray *stringArray2 = [formString componentsSeparatedByString:@"\" method="];
    NSString *action = stringArray2[0];
    NSString *inputString = stringArray2[1];
    NSArray *stringArray3 = [inputString componentsSeparatedByString:@"input"];
    
    // Get SAMLResponse
    NSArray *stringArray4 = [stringArray3[1] componentsSeparatedByString:@"\""];
    NSString *samlResponse = stringArray4[5];
    DDLogVerbose(@"SAMLResponse is: %@", samlResponse);
    
    // Get RelayState
    NSArray *stringArray5 = [stringArray3[2] componentsSeparatedByString:@"=\""];
    NSArray *stringArray6 = [stringArray5[3] componentsSeparatedByString:@"\""];
    NSString *relayState = stringArray6[0];
    DDLogVerbose(@"RelayState is: %@", relayState);
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:action]];
    [request setHTTPMethod:@"POST"];
    
    /*  THIS STATEMENT CORRECTED MY 'Unable to decode Base64 in POST
     binding
     message' ERROR
     There seems to be a shortage of URL Encoding features in
     Cocoa -
     Fortunately the '+' is the
     only character base64 has to worry about it seems
     */
    
//    NSString *encodeRelayState = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil,(CFStringRef)relayState, nil, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    
    NSString *encodeRelayState = [relayState stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ."]];
    
//    NSString *encodeSAMLResponse = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef)samlResponse, nil, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    
    NSString *encodeSAMLResponse = [samlResponse stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ."]];
    
    NSString *httpBody = @"RelayState=";
    httpBody = [httpBody stringByAppendingString:encodeRelayState];
    httpBody = [httpBody stringByAppendingString:@"&"];
    httpBody = [httpBody stringByAppendingString:@"SAMLResponse="];
    httpBody = [httpBody stringByAppendingString:encodeSAMLResponse];
    
    NSData *httpBodyData = [httpBody
                            dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *httpContentLength = [NSString stringWithFormat:@"%lu",
                                   (unsigned long)[httpBodyData length]];
    [request setValue:httpContentLength forHTTPHeaderField:@"Content-Length"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPBody:httpBodyData];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    operation.responseSerializer = [AFHTTPResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        DDLogVerbose(@"SignInWithSAML result:\n %@", result);
        
        [[CookieUtil sharedInstance] printCookie:HOST];
        DrawerTableViewController *leftSideDrawerViewController = [[DrawerTableViewController alloc] init];
        leftSideDrawerViewController.delegate = self;
        
        MarketWatchTableViewController *marketWatchViewController = [[MarketWatchTableViewController alloc] init];
        self.marketCenterViewController = [[MarketNavigationController alloc] initWithRootViewController:marketWatchViewController];
        
        self.drawerController = [[MMDrawerController alloc] initWithCenterViewController:self.marketCenterViewController leftDrawerViewController:leftSideDrawerViewController];
        [self.drawerController setShowsShadow:NO];
        [self.drawerController setRestorationIdentifier:@"MMDrawer"];
        [self.drawerController setMaximumLeftDrawerWidth:220.0];
        [self.drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModePanningNavigationBar];
        [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
        [self presentViewController:self.drawerController animated:YES completion:nil];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        DDLogError(@"SignInWithSAML error: %@", error);
        NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        DDLogError(@"SignInWithSAML error Message:\n %@", result);
    }];
    [[NSOperationQueue mainQueue] addOperation:operation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Text field delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Setting Rotate

// Login view only support portrait
- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown);
}

- (void)responseWithIndex:(NSInteger)index {
    switch (index) {
        case 1:
        {
            [self.drawerController setCenterViewController:self.marketCenterViewController];
            [self.drawerController closeDrawerAnimated:YES completion:nil];
            break;
        }
        case 2:
        {
            if (self.economicCenterViewController == nil) {
                EconomicCalendarViewController *economicViewController = [[EconomicCalendarViewController alloc] init];
                self.economicCenterViewController = [[EconomicCalendarNavigationController alloc] initWithRootViewController:economicViewController];
            }
            
            [self.drawerController setCenterViewController:self.economicCenterViewController];
            [self.drawerController closeDrawerAnimated:YES completion:nil];
            break;
        }
        case 3:
        {
            if (self.marketFlowCenterViewController == nil) {
                MarketFlowViewController *marketFlowViewController = [[MarketFlowViewController alloc] init];
                self.marketFlowCenterViewController = [[MarketFlowNavigationController alloc] initWithRootViewController:marketFlowViewController];
            }
            
            [self.drawerController setCenterViewController:self.marketFlowCenterViewController];
            [self.drawerController closeDrawerAnimated:YES completion:nil];
            break;
        }
        case 4:
        {
            [[MessageUtil sharedInstance] systemIsUpgrading];
            break;
        }
        case 5:
        {
            [[MessageUtil sharedInstance] systemIsUpgrading];
            break;
        }
        case 6:
        {
            if (self.contactCenterViewController == nil) {
                ContactViewController *contactViewController = [[ContactViewController alloc] init];
                self.contactCenterViewController = [[ContactNavigationController alloc] initWithRootViewController:contactViewController];
            }
            
            [self.drawerController setCenterViewController:self.contactCenterViewController];
            [self.drawerController closeDrawerAnimated:YES completion:nil];
            break;
        }
        case 7:
        {
            if (self.aboutCenterViewController == nil) {
                AboutViewController *aboutViewController = [[AboutViewController alloc] init];
                self.aboutCenterViewController = [[AboutNavigationController alloc] initWithRootViewController:aboutViewController];
            }
            
            [self.drawerController setCenterViewController:self.aboutCenterViewController];
            [self.drawerController closeDrawerAnimated:YES completion:nil];
            break;
        }
        case 8:
        {
            [self.drawerController dismissViewControllerAnimated:YES completion:nil];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
            [manager GET:@"https://www.sumridge.com/logout.php" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                [[CookieUtil sharedInstance] deleteCookie:HOST];
                [[CookieUtil sharedInstance] printCookie:HOST];
                [[CookieUtil sharedInstance] deleteCookie:@"https://login.mycroftcloud.com"];
                [[CookieUtil sharedInstance] printCookie:@"https://login.mycroftcloud.com"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                DDLogVerbose(@"Logout string is %@", responseString);
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                DDLogError(@"Logout Error: %@", error);
                NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
                DDLogError(@"Logout Result: %@", result);
            }];
            break;
        }
        default:
            break;
    }
}

@end
